<?php
/**
 * Description of PostsController
 *
 * @author luigi.pastore
 * @created  4-mag-2011
 */
class PostsController extends Classes_Controller
{
    public function init()
    {
	$this->model_post	= new Classes_Post();
	$this->model_category	= new Classes_Category;

	$this->layout->categories = $this->model_category->fetchAll();

	// Edit...
	if( is_numeric( $id = $this->getParam( 'id' ) ) )
	{
	    // Fetch
	    $post = $this->model_post->fetchById( array( $id ) );

	    if( empty( $post ) )
		trigger_error( 'Nessun Post' );
	    
	    $this->post = array_shift( $post );

            if( !empty( $this->post ) )
	    {
		# Formattiamo campi
		list( $this->post['post_published_d'], $this->post['post_published_m'], $this->post['post_published_y'] ) = explode( '-', $this->post['post_published_ita'] );
		//$_SESSION['Post']['Info'] = $this->post;
	    }	             
            
	    # Assegniamo i dati al layout
	    $this->layout->data = $this->post;

	    $this->layout->post_id = $this->post['post_id'];
	}        
    }
    
    public function indexAction()
    {
	$this->layout->content = array( 'script' => 'posts/index' );
    }
    
    public function infoAction()
    {
	$form_data = $this->getParams();
        
	if( $form_data['salva'] AND $form_data['salva'] !== '' )
	{
	    $this->layout->data = $form_data;

            // Mapping...
            $data = array(
                'post_id'               => $this->post['post_id'],
                'post_title'            => $form_data['post_title'],
                'post_text'             => $form_data['post_text'],
                'post_tags'             => $form_data['post_tags'],
                'post_published'        => $form_data['year'] . '-' . $form_data['month'] . '-' . $form_data['day'],
            );

            // Edit o Aggiunta?
            if( empty( $this->post ) )
                $data['post_createdby'] = $this->application->auth->user['user_id'];
            else
                $data['post_modifiedby'] = $this->application->auth->user['user_id'];

            $model = new Classes_Post( $data );

            if( is_numeric( $post_id = $model->save($form_data['post_category'])->post_id ) )
            {
                // Redirect...
                return header( 'Location: /admin/posts/immagine/id/'. $post_id );
            }
            else
            {
                if( $model->errors['post_title'] )
                    $errorMsg['post_title'] = sprintf( ERR_FORMAT, 'Titolo' );

                if( $model->errors['post_text'] )
                    $errorMsg['post_text'] = ERR_EMPTY;

                if( $model->errors['post_category'] )
                    $errorMsg['post_category'] = sprintf( ERR_EMPTY_SELECT, 'Titolo' );

                if(  $model->errors['post_published'] )
                    $errorMsg['post_published'] = ERR_DATE;

            }          
	}

	# Assegniamo i dati al layout
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'posts/info' );
    }

    public function immagineAction()
    {
       	if( is_null( $this->post ) )
	{
	    trigger_error( 'Errore Post' );
	}
        
	$form_data = $this->getParams();
        
	if( $form_data['salva'] AND $form_data['salva'] !== '' )
	{
	    // Validiamo server-side...
	    //$errorMsg = $this->checkFormData( $form_data );
	    
	    // Immagine
            if( $form_data['image'] == 'new')
            {
                $this->uploader = new Classes_Upload( $_FILES['post_image'] );
            }

            // Se è stata caricata un'immagine...
            if( $this->uploader->uploaded )
            {
                $errorMsg = $this->handleImage( $this->post['post_id'], true );

                if( !$errorMsg )
                {
                    if( is_null( $this->post['post_image_ext'] ) )
                    {
                        // Nuovo
                        // Setto a mano i dati relativi alla modifica, perchè non si tratta di una modifica vera e propria...
                        $model = new Classes_Post( 
                            array( 'post_id' => $this->post['post_id'],
                                   'post_modified' => $this->post['post_modified'],
                                   'post_modifiedby' => $this->application->auth->user['user_id'],
                                   'post_image_ext' => $this->uploader->file_dst_name_ext ) 
                            );
                    }
                    else
                    {

                        // Edit
                        // Setto a mano i dati relativi alla modifica, perchè non si tratta di una modifica vera e propria...
                        $model = new Classes_Post( 
                            array( 'post_id' => $this->post['post_id'],
                                   'post_modified' => new Classes_SqlExpression( 'NOW()' ), // Forzo la modifica perchè l'estensione dell'immagine potrebbe non cambiare, e quindi Mysql non riconoscerebbe la modifica (e non aggiornerebbe automaticamente il campo timepstamp)
                                   'post_modifiedby' => $this->application->auth->user['user_id'],
                                   'post_image_ext' => $this->uploader->file_dst_name_ext ) 
                            );                        
                    }
                    
                    if( is_numeric( $post_id = $model->save()->post_id ) )
                    {
                        // Redirect...
                        return header( 'Location: /admin/posts/anteprima/id/'. $post_id );
                    }
                    else
                    {
                        $errorMsg['post_image'] = 'Errore';
                        //return trigger_error( 'Errore Inserimento Post' );
                    }
                }
            }
            
            // Redirect...
            return header( 'Location: /admin/posts/anteprima/id/'. $this->post['post_id'] );
	} 
        
	# Assegniamo i dati al layout
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'posts/immagine' );	 
    }

    public function anteprimaAction()
    {
       	if( is_null( $this->post ) )
	    trigger_error( 'Errore Post' );
        
	# Assegniamo i dati al layout
        $this->layout->data     = $this->post;
	$this->layout->content  = array( 'script' => 'posts/anteprima' );	         
    }


//    public function nuovoAction()
//    {
//	if( $_POST['salva'] AND $_POST['salva'] !== '' )
//	{
//	    $this->layout->data = $_POST;
//
//	    // Validiamo server-side...
//	    $errorMsg = $this->checkFormData( $_POST );
//	    
//	    // Immagine
//	    if( !$errorMsg AND $_FILES['post_image']['name'] != '' )
//	    {
//		$this->uploader = new Classes_Upload( $_FILES['post_image'] );
//		
//		$errorMsg = $this->handleImage( null, false );
//	    }
//	    
//	    if( !$errorMsg )
//	    {
//		# Mapping...
//		$data = array(
//		    'post_title' => $_POST['post_title'],
//		    'post_text' => $_POST['post_text'],
//		    'post_tags' => $_POST['post_tags'],
//		    'post_createdby' => $this->application->auth->user['user_id'],
//		    'post_category' => $_POST['post_category'],
//		    'post_published' => $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'],
//		    'post_image_ext' => $this->uploader->file_dst_name_ext
//		);
//		
//		$model = new Classes_Post( $data );
//
//		if( is_numeric( $post_id = $model->save()->post_id ) )
//		{
//		    if( $this->uploader )
//		    {
//			$errorMsg = $this->handleImage( $post_id, true );
//		    }
//		    
//		    if( !$errorMsg )
//		    {
//			// Rimanda alla pagina di conferma...
//			$this->layout->forward = 'posts/';
//
//			return $this->layout->content = array( 'script' => 'completed' );
//		    }
//		}
//		else
//		{
//		    trigger_error( 'Errore Inserimento Post' );
//		}
//	    }
//	}
//
//	$this->layout->errorMsg = $errorMsg;
//	$this->layout->content = array( 'script' => 'posts/nuovo' );
//    }
//
//    public function editAction()
//    {
//	// Edit
//	if( !is_null( $this->getParam( 'id' ) ) )
//	{
//	    // Fetch
//	    $post = $this->model_post->fetchById( (int) $this->getParam( 'id' ) );
//
//	    // Se non c'è il post lancia l'errore
//	    if( !is_array( $post ) )
//	    {
//		trigger_error( 'Errore Edit Post', E_USER_WARNING );
//	    }
//	    else
//	    {
//		# Format Data
//		list( $post['day'], $post['month'], $post['year'] ) = explode( '-', $post['post_published'] );
//		
//		# Assegniamo i dati del post al layout
//		$this->layout->data = $post;
//	    }
//	}
//	
//	if( $_POST['salva'] AND $_POST['salva'] !== '' )
//	{
//	    $this->layout->data = $_POST;
//
//	    // Validiamo server-side...
//	    $errorMsg = $this->checkFormData( $_POST );
//	    
//	    // Immagine
//	    if( !$errorMsg AND $_FILES['post_image']['name'] != '' )
//	    {
//		$this->uploader = new Classes_Upload( $_FILES['post_image'] );
//		
//		$errorMsg = $this->handleImage( null, false );
//	    }
//	    
//	    if( !$errorMsg )
//	    {
//
//		$data = array(
//		    'post_id' => $post['post_id'],
//		    'post_title' => $_POST['post_title'],
//		    'post_text' => $_POST['post_text'],
//		    'post_tags' => $_POST['post_tags'],
//		    'post_modifiedby' => $this->application->auth->user['user_id'],
//		    'post_category' => $_POST['post_category'],
//		    'post_published' => $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day']
//		);
//
//		
//		// Se è stata caricata un'immagine aggiorna, altrimenti no...
//		if( $this->uploader )
//		    $data['post_image_ext'] = $this->uploader->file_dst_name_ext;
//		else
//		    $data['post_image_ext'] = $post['post_image_ext'];
//		
//		$model = new Classes_Post( $data );
//
//		if( is_numeric( $post_id = $model->save()->post_id ) )
//		{
//		    if( $this->uploader )
//		    {
//			$errorMsg = $this->handleImage( $post_id, true );
//		    }
//		    
//		    if( !$errorMsg )
//		    {
//			// Rimanda alla pagina di conferma...
//			$this->layout->forward = 'posts/';
//
//			return $this->layout->content = array( 'script' => 'completed' );
//		    }
//		}
//		else
//		{
//		    trigger_error( 'Errore Inserimento Post' );
//		}
//	    }
//	}
//
//	$this->layout->errorMsg = $errorMsg;
//	$this->layout->content = array( 'script' => 'posts/edit' );
//    }
    
    public function archivioAction()
    {
//        echo "<pre>";
//        var_dump($this->model_post->fetchAll());
//        echo "</pre>";
//        exit;
//	$this->layout->posts = $this->model_post->fetchAll();
	$this->layout->content = array( 'script' => 'posts/archivio' );
    }
    
    private function checkFormData( $data )
    {
	if( !filter_var( $_POST['post_title'], FILTER_SANITIZE_STRING ) )
	    $errorMsg['post_title'] = sprintf( ERR_FORMAT, 'Titolo' );

	if( !filter_var( $_POST['post_text'], FILTER_SANITIZE_SPECIAL_CHARS ) )
	    $errorMsg['post_text'] = ERR_EMPTY;

	if( !checkdate( $_POST['month'], $_POST['day'], $_POST['year'] ) )
	    $errorMsg['post_published'] = ERR_DATE;

	return $errorMsg ? $errorMsg : false;
    }
    
    private function handleImage( $post_id, $process = false )
    {
	if( $this->uploader->uploaded )
	{
	    // L'immagine è stata caricata correttamente...
	    $this->uploader->allowed = array( 'image/*' );
	    $this->uploader->image_min_width = POST_IMAGE_MIN_WIDTH;
	    $this->uploader->file_safe_name = false;
	    $this->uploader->file_auto_rename = false;
	    $this->uploader->file_overwrite = true;
	    $this->uploader->jpeg_quality = 72;

	    if( $this->uploader->image_src_x > POST_IMAGE_MAX_WIDTH )
	    {
		$this->uploader->image_resize = true;
		$this->uploader->image_x = POST_IMAGE_MAX_WIDTH;
		$this->uploader->image_ratio_y = true;
	    }

	    // Processa?
	    if( $process === true )
	    {
		// Rinomina e carica...
		$this->uploader->file_new_name_body = 'post_' . $post_id;
		$this->uploader->process( UPLOAD_DIR .'/posts/' );

		if( $this->uploader AND !$this->uploader->processed )
		{
		    // Aggiungi l'errore
		    $errorMsg['post_image'] = $this->uploader->error;
		}

                // Rimuove file temporanei..
                @unlink( UPLOAD_DIR . '/temp/post_' . $post_id . '.' . $this->uploader->file_dst_name_ext );
			
		$this->uploader->clean();
	    }
	    else
	    {
		$this->uploader->process();
            }

	    // Tutto ok?
	    if( !$this->uploader->processed )
	    {
		# Aggiungi l'errore
		$errorMsg['post_image'] = $this->uploader->error;
	    }
	}
	else
	{
	    // Aggiungi l'errore
	    $errorMsg['post_image'] = $this->uploader->error;	    
	}

	return $errorMsg ? $errorMsg : false;
    }    
}
